import 'package:flutter_app/bean/list_self_sign_collect_entity.dart';
import 'package:flutter_app/network/Api.dart';
import 'package:flutter_app/network/ResultData.dart';
import 'package:flutter_app/ui/apply/apply_detail/apply_detail_view.dart';
import 'package:flutter_app/utils/toast_utils.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'my_apply_state.dart';

class MyApplyLogic extends GetxController {
  final MyApplyState state = MyApplyState();

  late RefreshController refreshController;

  late int currentPage = 1;

  @override
  void onInit() {
    super.onInit();
    refreshController = new RefreshController(initialRefresh: false);
  }

  @override
  void onReady() {
    super.onReady();
    postListSelfSignCollect(currentPage);
  }

  /// 刷新
  void onRefresh() async {
    currentPage = 1;
    // 监视网络获取
    await Future.delayed(Duration(milliseconds: 1000));
    // 如果失败,使用refreshFailed ()
    postListSelfSignCollect(currentPage).then((value){
      refreshController.refreshCompleted();
      refreshController.resetNoData();
    });
  }

  /// 加载
  void onLoading() async{
    // 监视网络获取
    await Future.delayed(Duration(milliseconds: 1000));
    // 如果完成使用loadFailed()，如果没有数据返回，使用LoadNodata()
    int? totalPages = state.listSelfSignCollectEntity?.totalPages ?? 1;
    if (currentPage < totalPages) {
      currentPage++;
      postListSelfSignCollect(currentPage).then((value) => refreshController.loadComplete());
    } else {
      refreshController.loadNoData();
    }
  }


  /// 获取我的报名列表
  Future<void> postListSelfSignCollect(int currentPage) async {
    Map<String, dynamic> param = {
      "currentPage": currentPage,
      'pageSize': 15,
      'param': ""
    };

    ResultData resultData = await Api.postListSelfSignCollect(param);
    if (resultData.isSuccess) {
      if (currentPage == 1) {
        state.listSelfSignCollectEntity = ListSelfSignCollectEntity.fromJson(resultData.data['data']);
      } else if (currentPage > 1) {
        state.listSelfSignCollectEntity?.content?.addAll(
            ListSelfSignCollectEntity.fromJson(resultData.data['data']).content!);
      }
    } else {
      toast.show(resultData.data["message"]);
    }
    update();
  }

  void goToApplyDetailPage(String? collectId) {
    Get.to(() => ApplyDetailPage(title: "报名详情",), arguments: collectId);
  }

  @override
  void onClose() {
    super.onClose();
  }
}
